<template>
    <el-dialog :model-value="visible" title="手动调仓" @update:model-value="$emit('update:visible', $event)" width="50%">
        <el-form :model="form" ref="adjustmentFormRef" label-width="100px">
            <el-form-item label="调仓原因" prop="reason" :rules="{ required: true, message: '调仓原因不能为空', trigger: 'blur' }">
                <el-input type="textarea" v-model="form.reason"></el-input>
            </el-form-item>
            <div v-for="(detail, index) in form.details" :key="index">
                <el-form-item :label="'基金 ' + (index + 1)" :prop="'details.' + index + '.fundCode'"
                    :rules="{ required: true, message: '基金代码不能为空', trigger: 'blur' }">
                    <el-input v-model="detail.fundCode" placeholder="基金代码"
                        style="width: 45%; margin-right: 10px;"></el-input>
                    <el-input-number v-model="detail.weight" :precision="2" :step="0.01" :min="0" :max="100"
                        placeholder="目标权重(%)" style="width: 45%;"></el-input-number>
                    <el-button @click.prevent="removeDetail(index)" type="danger" link
                        style="margin-left: 10px;">删除</el-button>
                </el-form-item>
            </div>
            <el-form-item>
                <el-button @click="addDetail">新增基金</el-button>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="$emit('update:visible', false)">取消</el-button>
                <el-button type="primary" @click="submitAdjustment">确认调仓</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { performManualAdjustment } from '@/api/strategyApi';

const props = defineProps({
    visible: Boolean,
    strategyId: Number,
    initialComponents: {
        type: Array,
        default: () => []
    }
});

const emit = defineEmits(['update:visible', 'adjusted']);

const form = reactive({
    reason: '',
    details: [{ fundCode: '', weight: null }]
});
const adjustmentFormRef = ref(null);

watch(() => props.visible, (newVal) => {
    if (newVal) {
        // 当弹窗打开时，重置表单
        form.reason = '';
        if (props.initialComponents && props.initialComponents.length > 0) {
            // 如果传入了当前成分，则用它来填充表单
            form.details = props.initialComponents.map(comp => ({
                fundCode: comp.fund.code,
                weight: comp.weight
            }));
        } else {
            // 否则（如新建的策略），提供一个空行
            form.details = [{ fundCode: '', weight: null }];
        }
    }
});

const addDetail = () => {
    form.details.push({ fundCode: '', weight: null });
};

const removeDetail = (index) => {
    form.details.splice(index, 1);
};

const submitAdjustment = () => {
    adjustmentFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                await performManualAdjustment(props.strategyId, form);
                ElMessage.success('调仓成功');
                emit('adjusted');
                emit('update:visible', false);
            } catch (error) {
                ElMessage.error('调仓失败: ' + (error.response?.data?.message || error.message));
            }
        }
    });
};
</script>